package myapp.DAO;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import staticClass.MyRequest;

import android.util.Log;

import myapp.DTO.SubItemDTO;

public class SubItemDAO extends DataProvider{
	private final String url = "subitem/";
	
	public ArrayList<SubItemDTO> getAllSubItem(){
		String query = dbBaseHost + url;
		String strResponse = requestGET(query);
		return parseJsonToArr(strResponse);		
	}
	
	public void AddNewSubItem(SubItemDTO subitem){
		try {
			JSONObject json = subitem.toJson();
			String serverURL = dbBaseHost + "/subitem";
			MyRequest.postDataJson(serverURL, json);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private SubItemDTO jsonToSubItemDTO(JSONObject json){
		try {
			SubItemDTO s = new SubItemDTO(json.getInt("Id"),
					json.getString("Name"),
					json.getInt("ServiceId"),
					json.getString("Tags"),
					json.getString("Details"),
					json.getString("DateStart"),
					json.getString("DateFinish"));
			return s;
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("SubItemDAO", "[jsonToSubItemDTO] exception: "+e.getMessage() + " " + e.getLocalizedMessage());
		}
		
		Log.e("SubItemDAO", "[jsonToSubItemDTO] return null");
		return null;
	}
	
	private ArrayList<SubItemDTO> parseJsonToArr(String jsonResponse){
		JSONArray jsons;
		ArrayList<SubItemDTO> arr = new ArrayList<SubItemDTO>();
		
		Log.i("SubItemDAO", "[parseJSONArr] jsonStr: " + jsonResponse);
		
		if (jsonResponse == null)
			return arr;
		try {
			jsons = new JSONArray(jsonResponse);
			Log.i("SubItemDAO", "[parseJSONArr] jsonsLength = " + jsons.length());
			
			for (int i=0; i<jsons.length(); i++){
				arr.add(jsonToSubItemDTO(jsons.getJSONObject(i)));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.i("SubItemDAO", "[parseJSONArr] Exception: " + e.getMessage());
		}
		
		return arr;
	}
}